<?php

/**
 * Email utility.
 * @author Arlon
 *
 */
App::uses('CakeEmail', 'Network/Email');
App::uses('Multibyte', 'I18n');
class EmailUtility {

	/**
	 * $options[to] 多个时传入数组，收件人都能看到所有接收的邮箱
	 * @param unknown $options
	 * @param unknown $smtpoptions
	 * @return boolean|multitype:
	 */
    public function send($options= array(),$smtpoptions = array()){
    	$lib = new CakeEmail();
    	$lib->charset = 'utf-8';
    	$lib->headerCharset = 'utf-8';
    	
    	if( !empty($smtpoptions) ) {
    		$lib->transport(ucfirst('smtp'));
    		$lib->config($smtpoptions);
    		$options['from'] = Configure::read('Site.title').' '. '<' . $smtpoptions['username'] . '>';
    	}
    	else{
    	    $modelSmtp = loadModelObject('Smtp');
    	    $smtpdata = $modelSmtp->find('first',array(
    	        'conditions'=>array(
    	            'status' => 1,
    	        ),
    	        'order'=>'rand()',
    	        'recursive' => -1,
    	    ));
    	    
    	    if(!empty($smtpdata)) {
    	        
    	        $smtpoptions = array(
    	            'host' => $smtpdata['Smtp']['smtp_host'],
    	            'port' => $smtpdata['Smtp']['smtp_port'],
    	            'username' => $smtpdata['Smtp']['username'],
    	            'password' => $smtpdata['Smtp']['smtp_password'],
    	            'timeout' => 10,
    	            'tls' => $smtpdata['Smtp']['smtp_ssl'] ? true : false, //需要php安装open_ssl模块
    	        );
    	        
    	        $lib->transport(ucfirst('smtp'));
    	        $lib->config($smtpoptions);
    	        $options['from'] = Configure::read('Site.title').' '. '<' . $smtpoptions['username'] . '>';    	         
    	    }
    	    /*elseif( Configure::read('Email.smtp_host') &&
    	    	Configure::read('Email.smtp_port') &&
    	    	Configure::read('Email.smtp_username') &&
    	    	Configure::read('Email.smtp_pwd')
    	    	){
        		
        	    $users = array_filter( explode( ',',Configure::read('Email.smtp_username') ) );
        	    $pwds = array_filter( explode( ',',Configure::read('Email.smtp_pwd') ) );
        	    
        	    $idx = array_rand($users); // 从配置的多组邮箱中，随机选出一个来发送邮件
        		
        		$smtpoptions = array(
        				'host' => Configure::read('Email.smtp_host'),
        				'port' => Configure::read('Email.smtp_port'),
        				'username' => $users[$idx],
        				'password' => $pwds[$idx],
        				'timeout' => 10,
        				'tls' => Configure::read('Email.smtp_tls') ? true : false, //需要php安装open_ssl模块
        		);
        		
        		$lib->transport(ucfirst('smtp'));
        		$lib->config($smtpoptions);
        		$options['from'] = Configure::read('Site.title').' '. '<' . $smtpoptions['username'] . '>';
        	}*/
        	else{
        		$lib->transport(ucfirst('mail'));
        		$options['from'] = Configure::read('Site.title').' '. '<' . Configure::read('Site.email') . '>';
        	}
    	}
    	$lib->viewRender('Miao');
    	$lib->subject($options['subject'])->messageID(true);
    	$lib->helpers(array('Html','Js'));
    	
    	$options['layout']= $options['layout']?$options['layout']:'default';
    	
    	try{
    		
    		$lib->template($options['template'],$options['layout'])->viewVars($options['viewVars'])->emailFormat('both');
    		 
    		$lib->from($this->_formatAddresses((array)$options['from']));
    		if (!empty($options['to'])) {
    			$lib->to($this->_formatAddresses((array)$options['to']));
    		}
    		if (!empty($options['cc'])) {
    			$lib->cc($this->_formatAddresses((array)$options['cc']));
    		}
    		if (!empty($options['bcc'])) {
    			$lib->bcc($this->_formatAddresses((array)$options['bcc']));
    		}
    		if (!empty($options['replyTo'])) {
    			$lib->replyTo($this->_formatAddresses((array)$options['replyTo']));
    		}
    		
    		$sent =  $lib->send();
    	}
    	catch(SocketException $e){
    		Cakelog::alert($e->getMessage());
    		return false;
    	}
    	catch(Exception $e){
    		Cakelog::alert($e->getMessage());
    		return false;
    	}
    	return $sent;
    }
    
    /**
     * Format addresses to be an array with email as key and alias as value
     *
     * @param array $addresses
     * @return array
     */
    protected function _formatAddresses($addresses) {
    	$formatted = array();
    	foreach ($addresses as $address) {
    		if (preg_match('/((.*))?\s?<(.+)>/', $address, $matches) && !empty($matches[2])) {
    			$formatted[$this->_strip($matches[3])] = $matches[2];
    		} else {
    			$address = $this->_strip($address);
    			$formatted[$address] = $address;
    		}
    	}
    	return $formatted;
    }
    
    protected function _strip($value, $message = false) {
    	$search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:';
    	$search .= '|charset\=|mime-version\:|multipart/mixed|(?:[^a-z]to|b?cc)\:.*';
    
    	if ($message !== true) {
    		$search .= '|\r|\n';
    	}
    	$search = '#(?:' . $search . ')#i';
    	while (preg_match($search, $value)) {
    		$value = preg_replace($search, '', $value);
    	}
    	return $value;
    }
}
